﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.Data.OleDb;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data;
using System.IO;

namespace StudentModule.Views
{
    /// <summary>
    /// Interaction logic for ImportHinhAnhView.xaml
    /// </summary>
    public partial class ImportHinhAnhView : UserControl
    {
        VLUSMEntities entities = new VLUSMEntities();
        public ImportHinhAnhView()
        {
            InitializeComponent();
        }

        List<string> listpath = new List<string>();
        List<string> listname = new List<string>();

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog dlg = new OpenFileDialog();
                //dlg.DefaultExt = ".jpg";
                dlg.Filter = "Image File (.jpg)|*.jpg;*.png";
                dlg.Multiselect = true;
                if (dlg.ShowDialog() == true)
                {

                    textBox1.Text = dlg.FileName;
                    listpath = dlg.FileNames.ToList();
                    //duong dan cua file
                    foreach (string strName in dlg.FileNames)
                    {
                        listname.Add(System.IO.Path.GetFileName(strName).Replace(".jpg", ""));
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void button2_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < listpath.Count; i++)
            {
                string name = listname[i];
                SinhVien sv = entities.SinhViens.FirstOrDefault(c => c.MaSinhVien == name);
                if (sv != null)
                {
                    byte[] photo = GetPhoto(listpath[i]);
                    sv.HinhAnh = photo;
                }
            }
            entities.SaveChanges();
            label1.Content = "Import hình ảnh thành công!";
            label1.Foreground = Brushes.Blue;
        }



        public static byte[] GetPhoto(string filePath)
        {
            FileStream stream = new FileStream(
                filePath, FileMode.Open, FileAccess.Read);
            BinaryReader reader = new BinaryReader(stream);

            byte[] photo = reader.ReadBytes((int)stream.Length);

            reader.Close();
            stream.Close();

            return photo;
        }
    }
    
}
